#!/usr/bin/env python

import sys,os,re,time,urllib2
import threading,socket,shelve
import aiml

#sys.path.insert(0,moduledir)

os.chdir(os.path.abspath(__file__[0:-len(__file__.split("/")[len(__file__.split("/"))-1])]))

config = shelve.open("config.dat", writeback=1)


def finality(v,r):
	return str(v*r)

def compute(reg):
	global daft;
	print "thinking: "+reg.group(1)
	result = str(eval(reg.group(1)))
	print "thought: "+result
	return result

def defile(name):
	return re.sub("\..+$","",name)

def bailout():
	global config
	for mod in modules:
		modules[mod].stop()
	config.close()

sys.path.insert(0,"./aiml/");

# This is madness, rewrite using packages. Still here because it
# allows us to loop through all the plugin modules in a list
# also refactor to call them plugins not modules cause that's confusing

moduledir = './modules/'
sys.path.insert(0,moduledir)
modulelist = os.listdir(moduledir)
modules = {}
for mod in modulelist:
	#print "module "+mod+" has extension "+mod[-3:]+" !"
	if mod[-3:] == ".py":
		modules[mod[0:-3]] = __import__(mod[0:-3])
del sys.path[0]

#End madness.


class daft:

	def getc(self,key):
		global config
		if not config.has_key(key):
			return None
		else:
			return config.get(key)
	def setc(self,key,obj):
		global config
		config[key] = obj
		config.sync()

	def __init__(self):
		self.logLine("---session initiated "+time.ctime(time.time())+"---")
		self.k = aiml.Kernel() #create our aiml kernel
		aimldir = "./talk/" #what is our aimldirectory?
		self.dirList=os.listdir(aimldir) #whats in it?
		for fname in self.dirList:
			if re.match("[a-zA-Z0-9]+\.aiml$",fname):
				self.k.learn(aimldir+fname) #load everything in the dir into our brain

		self.testnet()
		self.phaser = []

	def reloadaiml(self):
		tempkernel = aiml.Kernel() #create our aiml kernel
		aimldir = "./talk/" #what is our aimldirectory?
		self.dirList=os.listdir(aimldir) #whats in it?
		for fname in self.dirList:
			if re.match("[a-zA-Z0-9]+\.aiml$",fname):
				tempkernel.learn(aimldir+fname)
		self.k = tempkernel

	def say(self,r,who,w):
		self.logLine('said: '+r+'\n')
		#print "saying: "+r+" to "+w+"\n"
		for mod in modules:
			modules[mod].say(self,r,who,w)
		return r

	def logLine(self,newLine): #take the line and chuck it on the end of the log
		log = open('log.txt','r+')
		loglines = ""
		for line in log:
			loglines = loglines + line +'\n' #I'm not sure how this works but we end up writing to the end of the file rather than the start, which works, I guess

		log.write(newLine+'\n')
		log.close
		return newLine

	def tick(self):
		for mod in modules:
			i = modules[mod].tick()
			if i:
				self.say(i)
		return None

	def boom(self,got,who,w):
		self.logLine(who+": "+got)
		got = re.sub("\.[\.\!\?]+"," AWKWARD ",got)
		chat = re.sub(" [QqSs]{2}[^a-sA-Z0-9$]+","? ",re.sub(" +"," ",re.sub("\[\[(.*?)\]\]",compute,re.sub("@[0-9]+",self.phasein,self.k.respond(re.sub("\"(.*?)\"",self.phaseout,got.replace("?"," qs. ")),who)))))
		self.phaser = []
		r = self.say(chat,who,w)
		return r

	def phaseout(self,message):
		self.phaser.append(message.group(1))
		return "@"+str(len(self.phaser))

	def phasein(self,message):
		return self.phaser.pop(0)
	
	def testnet(self):
		try:
			opener = urllib2.build_opener().addheaders = [('User-agent', 'Mozilla/5.0')].open('http://www.google.com')
			self.online = True
			self.say("I've connected to the internet.")
		except:
			self.online = False

	def checkonline(self):
		return self.online

daft = daft()
daft.modules = modules
for mod in modules:
	modules[mod].start(daft)

